<?php

namespace Home\Controller;

use Home\Controller\BaseController;

class PostController extends BaseController {

    public function _initialize() {
        $userToken = '';
        if (I("user_token")) {
            $userToken = I("user_token");
        }
        //查询库
        $where['user_token'] = $userToken;
        $userTokenInfo = M('Users')->where($where)->find();
        if ($userTokenInfo) {
            $this->user_id = $userTokenInfo['user_id'];
        }
    }

    public function getList() {
        $p = I('p', 0, 'intval');
        $size = I('psize', 15, 'intval');
        if ($p) {
            $page = $p * $size;
        }

        $is_system = I('is_system', 0, 'intval');

        $where['p.is_del'] = 0;
        $where['p.is_system'] = $is_system;

        $list = M()->table('ot_post p')
                ->field('p.post_id,p.title,p.post_type,p.post_style,p.topic_id,p.user_id,p.content,p.img_list,p.price,p.video_url,p.video_img,p.create_time,u.head_imgurl,u.nick_name,t.topic_name')
                ->join('left join ot_topic t on p.topic_id = t.topic_id')
                ->join('left join ot_users u on p.user_id = u.user_id')
                ->where($where)
                ->order('p.create_time desc')
                ->limit($page, $size)
                ->select();


        if ($list) {
            foreach ($list as &$val) {
                $val = formatPost($val, $this->user_id);
            }

            unset($val);
        } else {
            $list = [];
        }

        $total_page = M()->table('ot_post p')->where($where)->count();
        $data['total_page'] = ceil($total_page / $size);
        $data['list'] = $list;
        $this->success('获取成功', $data);
    }

    public function detail() {
        $id = I('id', 0, 'intval');

        if ($id == 0) {
            $this->error('请选择正确的帖子');
        }

        $p = I('p', 0, 'intval');
        $size = I('psize', 15, 'intval');
        if ($p) {
            $page = $p * $size;
        }

        $where['p.post_id'] = $id;
        $where['p.is_del'] = 0;

        $info = M()
                ->table('ot_post p')
                ->field('p.user_id,p.post_id,p.title,p.post_type,p.content,p.img_list,p.video_url,p.video_img,p.price,p.earnest,p.dog_sex,p.dog_brithday,p.hair_color,p.father_studbook,p.mother_studbook,p.father_chip_num,p.mother_chip_num,p.insect_record,p.vaccine_record,p.create_time,u.head_imgurl,u.nick_name,u.phone,p.is_system')
                ->join('left join ot_users u on p.user_id = u.user_id')
                ->where($where)
                ->find();

        if (empty($info)) {
            $this->error('帖子不存在或已删除');
        }

        $detail = formatPost($info, $this->user_id);

        if ($detail['post_type'] != 10) {
            $detail['zan_num'] = M('PostZan')->where(['post_id' => $detail['post_id']])->count();

            $detail['zan_face'] = M()->table('ot_post_zan pz')
                    ->join('left join ot_users u on pz.user_id = u.user_id')
                    ->where(['pz.post_id' => $detail['post_id']])
                    ->limit(0, 8)
                    ->getField('head_imgurl', true);

            $comment = M()->table('ot_post_comment pc')
                    ->field('pc.comment_id,pc.content,u.head_imgurl as comment_user_face,u.nick_name as comment_user_nick_name,pc.create_time')
                    ->join('left join ot_users u on pc.user_id = u.user_id')
                    ->where(['pc.post_id' => $detail['post_id']])
                    ->order('pc.create_time desc')
                    ->limit($page, $size)
                    ->select();

            if (!empty($comment)) {
                foreach ($comment as &$val) {
                    $val['recom'] = M()->table('ot_post_comment pc')
                            ->field('pc.comment_id as recom_id,pc.content as recom_content,u.nick_name as recom_user_nick_name')
                            ->join('left join ot_users u on pc.user_id = u.user_id')
                            ->where(['pc.recom_id' => $val['comment_id']])
                            ->order('pc.create_time desc')
                            ->select();

                    if (empty($val['recom'])) {
                        $val['recom'] = [];
                    }

                    $date = strtotime($val['create_time']);

                    $today = date('Y-m-d', time());
                    $zuotian = date("Y-m-d", strtotime("-1 day"));
                    $qiantian = date("Y-m-d", strtotime("-2 day"));
                    $create_time = date('Y-m-d', $date);

                    $date_time = date('H:i', $date);

                    if ($create_time == $today) {
                        $hours = intval((time() - $date) / 3600);
                        $val['comment_create_date'] = '刚刚';
                        if ($hours >= 1) {
                            $val['comment_create_date'] = $hours . '小时前';
                        }
                        $val['comment_create_time'] = $date_time;
                    } elseif ($create_time == $zuotian) {
                        $val['comment_create_date'] = '昨天';
                        $val['comment_create_time'] = $date_time;
                    } elseif ($create_time == $qiantian) {
                        $val['comment_create_date'] = '前天';
                        $val['comment_create_time'] = $date_time;
                    } else {
                        $val['comment_create_date'] = '3天前';
                        $val['comment_create_time'] = '';
                    }
                    unset($val['create_time']);

                    $comment_is_zan = M('PostZan')->where(['comment_id' => $val['comment_id'], 'user_id' => $this->user_id])->find();

                    $val['comment_is_zan'] = 0;
                    if ($comment_is_zan) {
                        $val['comment_is_zan'] = 1;
                    }

                    $val['comment_zan_num'] = M('PostZan')->where(['comment_id' => $val['comment_id']])->count();
                }
                unset($val);

                $detail['comment'] = $comment;
                $detail['insect_record'] = [];
                $detail['vaccine_record'] = [];
            }
        } else {
            $detail['zan_num'] = 0;
            $detail['comment'] = [];
            $detail['zan_face'] = [];
            if ($detail['insect_record']) {
                $detail['insect_record'] = unserialize($detail['insect_record']);
            }
            if ($detail['vaccine_record']) {
                $detail['vaccine_record'] = unserialize($detail['vaccine_record']);
            }
        }
        $detail['is_edit'] = 0;

        if (($detail['user_id'] == $this->user_id) && $this->user_id != 0) {
            $detail['is_edit'] = 1;
        }

        $is_collect = M('PostCollect')->where(['post_id' => $id, 'user_id' => $this->user_id])->find();

        $detail['is_collect'] = 0;

        if ($is_collect) {
            $detail['is_collect'] = 1;
        }

        $is_follow = M('UserFollow')->where(['follow_uid' => $detail['user_id'], 'user_id' => $this->user_id])->find();
//        unset($detail['user_id']);

        $detail['is_follow'] = 0;

        if ($is_follow) {
            $detail['is_follow'] = 1;
        }

        unset($info);

        $this->success('获取成功', $detail);
    }

    public function salePost() {
        $id = I('id', 0, 'intval');

        if ($id == 0) {
            $this->error('请选择正确的帖子');
        }

        $where['p.post_id'] = $id;
        $where['p.is_del'] = 0;
        $where['p.post_type'] = 10;

        $info = M()
                ->table('ot_post p')
                ->field('p.post_id,p.title,p.post_type,p.content,p.img_list,p.price,p.earnest,p.dog_sex,p.dog_brithday,p.hair_color,p.father_studbook,p.mother_studbook,p.father_chip_num,p.mother_chip_num,p.insect_record,p.vaccine_record,p.create_time,u.head_imgurl,u.nick_name,u.phone')
                ->join('left join ot_users u on p.user_id = u.user_id')
                ->where($where)
                ->find();

        if (empty($info)) {
            $this->error('帖子不存在或已删除');
        }

        $detail = formatPost($info, $this->user_id);

        unset($info);
        unset($detail['is_zan']);
        unset($detail['comment_num']);

        $detail['insect_record'] = unserialize($detail['insect_record']);
        $detail['vaccine_record'] = unserialize($detail['vaccine_record']);

        $this->success('获取成功', $detail);
    }

    public function zan() {
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $post_id = I('post_id', 0, 'intval');
        $comment_id = I('comment_id', 0, 'intval');

        if ($post_id == 0 && $comment_id == 0) {
            $this->error('请选择要点赞的内容');
        }

        $where['user_id'] = $this->user_id;
        if ($post_id != 0) {
            $where['post_id'] = $post_id;
        }

        if ($comment_id != 0) {
            $where['comment_id'] = $comment_id;
        }

        $is_zan = M('PostZan')->where($where)->find();

        $res = 0;
        if (empty($is_zan)) {
            $res = M('PostZan')->add($where);
        } else {
            $res = M('PostZan')->where($where)->delete();
        }

        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    public function comment() {
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $post_id = I('post_id', 0, 'intval');
        $comment_id = I('comment_id', 0, 'intval');

        if ($post_id == 0 && $comment_id == 0) {
            $this->error('请选择要回复的内容');
        }

        $content = I('content');

        if (empty($content)) {
            $this->error('回复内容不能为空!');
        }

        $where['content'] = $content;
        $where['user_id'] = $this->user_id;
        if ($post_id != 0) {
            $where['post_id'] = $post_id;
        }

        if ($comment_id != 0) {
            $where['recom_id'] = $comment_id;
        }

        $res = M('PostComment')->add($where);

        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    public function add() {
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }
        $type = 1;

        $title = I('title');
        $content = I('content');
        $img_url = I('img_url');
        $video_url = I('video_url');
        $data['topic_id'] = I('topic_id', 0, 'intval');
        if (empty($title)) {
            $this->error('请输入帖子标题');
        }

        $data['title'] = $title;
        $data['content'] = $content;
        $data['user_id'] = $this->user_id;
        \Think\Log::record("图片Base64:$img_url");
        if ($img_url) {
            $type = 2;
//            $img_list = explode(',', $img_url);
//
////            vendor('Image');
//            $up_img = array();
//            foreach ($img_list as $val) {
//                \Think\Log::record("图片:$val");
//                if (empty($val)) {
//                    continue;
//                }
//                $code = md5(time() + mt_rand(1, 9999));
//                $s = file_put_contents('./Uploads/Picture/' . $code . '.png', base64_decode($val)); //返回的是字节数
////
////                $src = "/Uploads/Picture/$code.png";
////
////                $src2 = "/Uploads/Picture/$code".'AAAAA.png';
////                $image = new \Image($src);
////                $image->percent = 0.2;
////                $image->openImage();
////                $image->thumpImage();
//////                $image->showImage();
////                $image->saveImage($src2);
////                
////                echo $src2;die;
////
//
//                $up_img[] = '/Uploads/Picture/' . $code . '.png';
//            }
//            $data['img_list'] = implode(',', $up_img);
            $data['img_list'] = $img_url;
//            \Think\Log::record('图片汇总' . implode(',', $up_img));
        }

        if ($video_url) {
            $type = 3;
            $data['video_url'] = $video_url;
//            $code = md5(time() + mt_rand(1, 9999));
//            $s = file_put_contents('./Uploads/Picture/' . $code . '.mp4', base64_decode($video_url)); //返回的是字节数
//            $data['video_url'] = '/Uploads/Picture/' . $code . '.mp4';
            $code = md5(time() + mt_rand(1, 9999));
            $img = '/Uploads/Picture/' . $code . '.jpg';
//            \Think\Log::record("视频:" . $img);
//            \Think\Log::record("图片:" . $data['video_url']);
            $input = dirname(dirname(dirname(dirname(__FILE__)))) . $data['video_url'];
            $output = dirname(dirname(dirname(dirname(__FILE__)))) . $img;

            $data['video_img'] = $img;
//            $res['post_id'] = M('Post')->add($data);
//
            $command = "ffmpeg -i $input -y -f image2 -ss 1 -vframes 1 $output";
            \Think\Log::record("执行命令:" . $command);
//            $output1 = '';
            $result = exec($command, $output1);
//            $this->success($res);
//
//            \Think\Log::record("命令返回:" . arrayToString($output1));
//            \Think\Log::record("命令返回:" . arrayToString($result));
        }
        $data['post_type'] = $type;
        $res['post_id'] = M('Post')->add($data);
        $this->success($res);
    }

    public function addSale() {
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $is_phone = M('Users')->where(['user_id' => $this->user_id])->getField('phone');

//        if (empty($is_phone) || $is_phone == 0) {
//            $this->error('请先完善手机号', '', 102);
//        }

        $data['post_type'] = 10;

        $title = I('title');
        $content = I('content');
        $img_url = I('img_url');
        $video_url = I('video_url');
        $price = I('price', 0);
        $earnest = I('earnest', 0);

        if (empty($title)) {
            $this->error('请输入帖子标题');
        }
        if ($price == 0) {
            $this->error('请输入售价');
        }

        if ($earnest == 0) {
            $this->error('请输入定金');
        }


        $data['title'] = $title;
        $data['content'] = $content;
        $data['price'] = $price;
        $data['earnest'] = $earnest;
        $data['dog_sex'] = I('dog_sex', 1);
        $data['dog_brithday'] = I('dog_brithday', '2017-10-01');
        $data['hair_color'] = I('hair_color');
        $data['father_studbook'] = I('father_studbook');
        $data['mother_studbook'] = I('mother_studbook');
        $data['father_chip_num'] = I('father_chip_num');
        $data['mother_chip_num'] = I('mother_chip_num');
        $insect_record = I('insect_record');
        $vaccine_record = I('vaccine_record');

        if (!empty($insect_record)) {
            $insect = [];
            $tmp = explode('&', $insect_record);

            foreach ($tmp as $v) {
                $v = explode('#', $v);
                if (count($v) != 2) {
                    $this->error('请填写完整的驱虫记录');
                }
                if ((!empty($v[0]) && !empty($v[1])) && ($v[0] != 'null' && $v[1] != 'null')) {
                    $insect[] = array('date' => $v[0], 'name' => $v[1]);
                }
            }

            $data['insect_record'] = serialize($insect);
        }

        if (!empty($vaccine_record)) {
            $vaccine = [];
            $tmp = explode('&', $vaccine_record);

            foreach ($tmp as $v) {
                $v = explode('#', $v);
                if (count($v) != 2) {
                    $this->error('请填写完整的疫苗记录');
                }
                if ((!empty($v[0]) && !empty($v[1])) && ($v[0] != 'null' && $v[1] != 'null')) {
                    $vaccine[] = array('date' => $v[0], 'name' => $v[1]);
                }
            }

            $data['vaccine_record'] = serialize($vaccine);
        }

        $data['content'] = $content;
        $data['user_id'] = $this->user_id;

        if ($img_url) {
            $data['img_list'] = $img_url;
//            $img_list = explode(',', $img_url);
//
//            $up_img = array();
//            foreach ($img_list as $val) {
//                \Think\Log::record("图片:$val");
//                if (empty($val)) {
//                    continue;
//                }
//                $code = md5(time() + mt_rand(1, 9999));
//                $s = file_put_contents('./Uploads/Picture/' . $code . '.png', base64_decode($val)); //返回的是字节数
//                $up_img[] = '/Uploads/Picture/' . $code . '.png';
//            }
//
//            $data['img_list'] = implode(',', $up_img);
//            \Think\Log::record('图片汇总' . implode(',', $up_img));
        }

        if ($video_url) {
            $data['video_url'] = $video_url;

            $code = md5(time() + mt_rand(1, 9999));
            $img = '/Uploads/Picture/' . $code . '.jpg';
            $input = dirname(dirname(dirname(dirname(__FILE__)))) . $data['video_url'];
            $output = dirname(dirname(dirname(dirname(__FILE__)))) . $img;

            $data['video_img'] = $img;
//
            $command = "ffmpeg -i $input -y -f image2 -ss 1 -vframes 1 $output";
            \Think\Log::record("执行命令:" . $command);
            $result = exec($command, $output1);
        }

        $res['post_id'] = M('Post')->add($data);
        $this->success($res);
    }

    public function edit() {
        $id = I('id', 0, 'intval');
        if ($id == 0) {
            $this->error('请选择正确的帖子');
        }
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $is_edit = M('Post')->where(['post_id' => $id, 'user_id' => $this->user_id])->find();

        if (empty($is_edit)) {
            $this->error('不是你的帖子不允许编辑');
        }

        $type = 1;

        $title = I('title');
        $content = I('content');
        $img_url = I('img_url');
        $video_url = I('video_url');
        $data['topic_id'] = I('topic_id', 0, 'intval');
        if (empty($title)) {
            $this->error('请输入帖子标题');
        }

        $data['title'] = $title;
        $data['content'] = $content;
        $data['user_id'] = $this->user_id;
        \Think\Log::record("图片Base64:$img_url");
        if ($img_url) {
            $type = 2;
            $data['img_list'] = $img_url;
//            $img_list = explode(',', $img_url);
//
////            vendor('Image');
//            $up_img = array();
//            foreach ($img_list as $val) {
//                \Think\Log::record("图片:$val");
//                if (empty($val)) {
//                    continue;
//                }
//                if (is_base_64($val)) {
//                    $code = md5(time() + mt_rand(1, 9999));
//                    $s = file_put_contents('./Uploads/Picture/' . $code . '.png', base64_decode($val)); //返回的是字节数
//                    $up_img[] = '/Uploads/Picture/' . $code . '.png';
//                } else {
//                    $up_img[] = $val;
//                }
//            }
//
//            $data['img_list'] = implode(',', $up_img);
//            \Think\Log::record('图片汇总' . implode(',', $up_img));
        }

        if ($video_url) {
            $type = 3;
            $data['video_url'] = $video_url;
            $code = md5(time() + mt_rand(1, 9999));
            $img = '/Uploads/Picture/' . $code . '.jpg';
            $input = dirname(dirname(dirname(dirname(__FILE__)))) . $data['video_url'];
            $output = dirname(dirname(dirname(dirname(__FILE__)))) . $img;

            $data['video_img'] = $img;
//
            $command = "ffmpeg -i $input -y -f image2 -ss 1 -vframes 1 $output";
            \Think\Log::record("执行命令:" . $command);
            $result = exec($command, $output1);
        }
        $data['post_type'] = $type;
        $res = M('Post')->where(['post_id' => $id])->save($data);
        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    public function editSale() {
        $id = I('id', 0, 'intval');
        if ($id == 0) {
            $this->error('请选择正确的帖子');
        }
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $is_edit = M('Post')->where(['post_id' => $id, 'user_id' => $this->user_id])->find();

        if (empty($is_edit)) {
            $this->error('不是你的帖子不允许编辑');
        }

        $data['post_type'] = 10;

        $title = I('title');
        $content = I('content');
        $img_url = I('img_url');
        $video_url = I('video_url');
        $price = I('price', 0);
        $earnest = I('earnest', 0);

        if (empty($title)) {
            $this->error('请输入帖子标题');
        }
        if ($price == 0) {
            $this->error('请输入售价');
        }

        if ($earnest == 0) {
            $this->error('请输入定金');
        }


        $data['title'] = $title;
        $data['content'] = $content;
        $data['price'] = $price;
        $data['earnest'] = $earnest;
        $data['dog_sex'] = I('dog_sex', 1);
        $data['dog_brithday'] = I('dog_brithday', '2017-10-01');
        $data['hair_color'] = I('hair_color');
        $data['father_studbook'] = I('father_studbook');
        $data['mother_studbook'] = I('mother_studbook');
        $data['father_chip_num'] = I('father_chip_num');
        $data['mother_chip_num'] = I('mother_chip_num');
        $insect_record = I('insect_record');
        $vaccine_record = I('vaccine_record');

        if (!empty($insect_record)) {
            $insect = [];
            $tmp = explode('&', $insect_record);

            foreach ($tmp as $v) {
                $v = explode('#', $v);
                if (count($v) != 2) {
                    $this->error('请填写完整的驱虫记录');
                }
                if ((!empty($v[0]) && !empty($v[1])) && ($v[0] != 'null' && $v[1] != 'null')) {
                    $insect[] = array('date' => $v[0], 'name' => $v[1]);
                }
            }


            $data['insect_record'] = serialize($insect);
        }

        if (!empty($vaccine_record)) {
            $vaccine = [];
            $tmp = explode('&', $vaccine_record);

            foreach ($tmp as $v) {
                $v = explode('#', $v);
                if (count($v) != 2) {
                    $this->error('请填写完整的疫苗记录');
                }
                if ((!empty($v[0]) && !empty($v[1])) && ($v[0] != 'null' && $v[1] != 'null')) {
                    $vaccine[] = array('date' => $v[0], 'name' => $v[1]);
                }
            }

            $data['vaccine_record'] = serialize($vaccine);
        }

        $data['content'] = $content;
        $data['user_id'] = $this->user_id;

        $data['img_list'] = $img_url;

        if ($video_url) {
            $data['video_url'] = $video_url;
            $code = md5(time() + mt_rand(1, 9999));
            $img = '/Uploads/Picture/' . $code . '.jpg';
            $input = dirname(dirname(dirname(dirname(__FILE__)))) . $data['video_url'];
            $output = dirname(dirname(dirname(dirname(__FILE__)))) . $img;

            $data['video_img'] = $img;
//
            $command = "ffmpeg -i $input -y -f image2 -ss 1 -vframes 1 $output";
            \Think\Log::record("执行命令:" . $command);
            $result = exec($command, $output1);
        } else {
            $data['video_url'] = '';
            $data['video_img'] = '';
        }

        $res = M('Post')->where(['post_id' => $id])->save($data);
        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    public function del() {
        $id = I('id', 0, 'intval');
        if ($id == 0) {
            $this->error('请选择正确的帖子');
        }
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $where['post_id'] = $id;
        $where['user_id'] = $this->user_id;

        $is_edit = M('Post')->where($where)->find();

        if (empty($is_edit)) {
            $this->error('不是你的帖子不允许删除');
        }

        $res = M('Post')->where(['post_id' => $id])->save(['is_del' => 1]);
        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

    public function collectOrCancel() {
        if ($this->user_id == 0) {
            $this->error('请登录', '', 101);
        }

        $post_id = I('post_id', 0, 'intval');

        if ($post_id == 0) {
            $this->error('请选择正确的帖子');
        }

        $is_my_post = M('Post')->where(['post_id' => $post_id, 'user_id' => $this->user_id])->find();

        if ($is_my_post) {
            $this->error('自己的帖子不可以收藏');
        }

        $is_collect = M('PostCollect')->where(['post_id' => $post_id, 'user_id' => $this->user_id])->find();

        $res = 0;
        if ($is_collect) {
            $res = M('PostCollect')->where(['collect_id' => $is_collect['collect_id']])->delete();
        } else {
            $data['post_id'] = $post_id;
            $data['user_id'] = $this->user_id;
            $res = M('PostCollect')->add($data);
        }

        if ($res) {
            $this->success();
        } else {
            $this->error();
        }
    }

}
